<template>
  <div class="project-row">
    <div class="project-id">
      {{ project.id }}
    </div>
    <div class="project-info">
      <h4>{{ project.customer_name }}</h4>
      <p>{{ project.customer_domain }}</p>
      <span class="project-code">{{ project.project_code }}</span>
    </div>
    <div class="manager-info">{{ project.customer_manager || '-' }}</div>
    <div>
      <span class="status-badge" :class="statusConfig[project.vika_status]?.class || 'pending'">
        {{ statusConfig[project.vika_status]?.text || project.vika_status }}
      </span>
    </div>
    <div class="items-summary">
      <div v-if="!project.contract_requirements || project.contract_requirements.length === 0" class="no-items">
        暂无条目
      </div>
      <div v-else>
        <div v-for="requirement in project.contract_requirements" :key="requirement.id" class="item-row">
          <div class="item-header">
            <div class="item-name">{{ requirement.requirement_type }}</div>
            <span class="item-status" :class="getItemStatusByProgress(requirement.requirement_type).class">
              {{ getItemStatusByProgress(requirement.requirement_type).text }}
            </span>
          </div>
          <div class="item-details">
            <span class="item-detail-tag item-quantity">总量: {{ requirement.target_quantity }}条</span>
            <span v-if="requirement.quality_requirements.da" class="item-detail-tag item-da">
              DA > {{ requirement.quality_requirements.da }}
            </span>
            <span v-if="requirement.quality_requirements.as" class="item-detail-tag item-as">
              AS > {{ requirement.quality_requirements.as }}
            </span>
            <span v-if="requirement.quality_requirements.count && requirement.requirement_type !== 'PR通稿'"
              class="item-detail-tag item-count">
              需要: {{ requirement.quality_requirements.count }}条
            </span>
            <span v-if="requirement.quality_requirements.count && requirement.requirement_type === 'PR通稿'"
              class="item-detail-tag item-count">
              覆盖: {{ requirement.quality_requirements.count }} 个站点
            </span>

            <span v-if="requirement.quality_requirements.dofollow" class="item-detail-tag item-dofollow">
              {{ 'Dofollow' }}
            </span>
          </div>
          <div class="item-progress">
            <div v-if="progressLoading" class="progress-loading">
              加载中...
            </div>
            <div v-else-if="progressError" class="progress-error">
              {{ progressError }}
            </div>
            <div v-else class="progress-content">
              <!-- 高价值外链的双色进度条 -->
              <div v-if="requirement.requirement_type === '高价值外链'" class="progress-bar dual-color"
                style="margin-top: 8px;">
                <div class="progress-fill-frozen"
                  :style="{ width: `${Math.round(getFrozenProgress(requirement.requirement_type))}%` }">
                </div>
                <div class="progress-fill-normal"
                  :style="{ width: `${Math.round(getNormalProgress(requirement.requirement_type))}%`, marginLeft: `${Math.round(getFrozenProgress(requirement.requirement_type))}%` }">
                </div>
              </div>
              <!-- 普通进度条 -->
              <div v-else class="progress-bar" style="margin-top: 8px;">
                <div class="progress-fill"
                  :style="{ width: `${Math.round(getRequirementProgress(requirement.requirement_type).completionRate)}%` }">
                </div>
              </div>

              <!-- 高价值外链的进度文本 -->
              <div v-if="requirement.requirement_type === '高价值外链'" class="progress-text">
                完成进度: {{ Math.round(getRequirementProgress(requirement.requirement_type).completionRate) }}%
                ({{ getRequirementProgress(requirement.requirement_type).completedQuantity }}/{{
                  getRequirementProgress(requirement.requirement_type).targetQuantity }})
                <div class="frozen-progress-info">
                  <span class="legend-color adsy"></span>

                  冻结进度: {{ Math.round(getFrozenProgress(requirement.requirement_type)) }}%
                  ({{ getFrozenCount(requirement.requirement_type) }}条)
                </div>
              </div>
              <!-- 普通进度文本 -->
              <div v-else class="progress-text">
                完成进度: {{ Math.round(getRequirementProgress(requirement.requirement_type).completionRate) }}%
                ({{ getRequirementProgress(requirement.requirement_type).completedQuantity }}/{{
                  getRequirementProgress(requirement.requirement_type).targetQuantity }})
              </div>
              <!-- 质量检查进度条 -->
              <div v-if="getQualityCheckData(requirement.requirement_type)" class="quality-progress">
                <div class="quality-progress-bar">
                  <div class="quality-progress-fill"
                    :style="{ width: `${getQualityCheckData(requirement.requirement_type).quality_rate}%` }">
                  </div>
                </div>
                <div class="quality-progress-text">
                  {{ getQualityCheckLabel(requirement.requirement_type) }} 进度: {{
                    getQualityCheckData(requirement.requirement_type).quality_rate }}%
                  ({{ getQualityCheckData(requirement.requirement_type).quality_completed }}/{{
                    getQualityCheckData(requirement.requirement_type).quality_target }})
                </div>
              </div>
            </div>
          </div>
          <div v-if="requirement.additional_notes" class="item-notes">
            {{ requirement.additional_notes }}
          </div>
        </div>
        <div class="items-total">
          <div class="total-amount">
            总计: {{ (parsePrice(progressData?.amount_usage?.total_price || props.project.contract_terms?.amount || 0) *
              8).toFixed(2) }} 积分
          </div>
          <!-- 金额使用情况 - 只有真实数据时才显示 -->
          <div v-if="progressData?.type_progress_data.金额使用" class="amount-usage">
            <div class="amount-usage-header">金额使用情况</div>
            <div class="amount-progress-bar">
              <div class="amount-segment freeze" :style="{ width: `${getAmountPercentage('freeze_price')}%` }"
                :title="`冻结: ${progressData?.type_progress_data.金额使用.freeze_price}`">
              </div>
              <!-- <div class="amount-segment submit" :style="{ width: `${getAmountPercentage('submit_price')}%` }"
                :title="`提交: ${progressData?.type_progress_data.金额使用.submit_price}`">
              </div> -->
              <div class="amount-segment confirm" :style="{ width: `${getAmountPercentage('confirm_price')}%` }"
                :title="`确认: ${progressData?.type_progress_data.金额使用.confirm_price}`">
              </div>
            </div>
            <div class="amount-legend">
              <span class="legend-item">
                <span class="legend-color freeze"></span>
                冻结: {{ (parsePrice(progressData?.type_progress_data.金额使用.freeze_price) * 8).toFixed(2) }} 积分
              </span>
              <!-- <span class="legend-item">
                <span class="legend-color submit"></span>
                提交: ${{ parsePrice(progressData?.type_progress_data.金额使用.submit_price).toFixed(2) }}
              </span> -->
              <span class="legend-item">
                <span class="legend-color confirm"></span>
                确认: {{ (parsePrice(progressData?.type_progress_data.金额使用.confirm_price) * 8).toFixed(2) }} 积分
              </span>
              <span class="legend-item">
                <span class="legend-color remaining"></span>
                剩余: {{ (parsePrice(progressData?.type_progress_data.金额使用.remaining_price) * 8).toFixed(2) }} 积分
              </span>
            </div>
          </div>


          <div class="completion-info">
            完成度: {{ getCompletedRequirementsCount() }}/{{ props.project.contract_requirements.length }} - 快照更新时间:
            {{ progressData?.snapshot_info.snapshot_date }}
          </div>
        </div>
      </div>
    </div>
    <div class="date-info">
      <div>开始: {{ formatDate(project.start_date) }}</div>
      <div>结束: {{ formatDate(project.end_date) }}</div>
      <div class="project-timeline">
        <div class="timeline-progress-bar">
          <div class="timeline-progress-fill" :style="{ width: `${getProjectTimeProgress()}%` }"></div>
        </div>
        <div class="timeline-text">
          时间进度: {{ getProjectTimeProgress() }}%
        </div>
      </div>
    </div>
    <div class="actions">
      <button class="action-btn primary" @click="$emit('view', project)">查看</button>
      <button class="action-btn" @click="$emit('edit', project)">编辑</button>
      <button class="action-btn warning" @click="$emit('trend', project)">趋势</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { Project, ProjectProgressData } from '../types'
import { progressApi } from '../api/services/progress'

const props = defineProps<{
  project: Project
}>()

defineEmits<{
  view: [project: Project]
  edit: [project: Project]
  trend: [project: Project]
}>()

// 进度数据
const progressData = ref<ProjectProgressData | null>(null)
const progressLoading = ref(false)
const progressError = ref<string | null>(null)

const statusConfig = {
  '未开始': { text: '未开始', class: 'pending' },
  '未达标': { text: '未达标', class: 'warning' },
  '已达标': { text: '已达标', class: 'completed' }
}

const itemStatusConfig = {
  PENDING: { text: '待处理', class: 'pending' },
  COMPLETED: { text: '已完成', class: 'completed' }
}

const formatDate = (dateStr: string | null) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

// 计算项目时间进度
const getProjectTimeProgress = () => {
  if (!props.project.start_date || !props.project.end_date) return 0

  const startDate = new Date(props.project.start_date)
  const endDate = new Date(props.project.end_date)
  const currentDate = new Date()

  // 如果当前时间在开始时间之前，进度为0
  if (currentDate < startDate) return 0

  // 如果当前时间在结束时间之后，进度为100
  if (currentDate > endDate) return 100

  // 计算进度百分比
  const totalDuration = endDate.getTime() - startDate.getTime()
  const elapsedDuration = currentDate.getTime() - startDate.getTime()

  return Math.round((elapsedDuration / totalDuration) * 100)
}

// 获取项目进度数据
const fetchProgressData = async () => {
  progressLoading.value = true
  progressError.value = null

  try {
    const result = await progressApi.getProjectProgressSafe(props.project.id)
    if (result.success) {
      progressData.value = result.data
    } else {
      progressError.value = result.error
    }
  } catch (error) {
    progressError.value = '获取进度数据失败'
  } finally {
    progressLoading.value = false
  }
}

// 获取特定需求类型的进度信息
const getRequirementProgress = (requirementType: string) => {
  if (!progressData.value?.type_progress_data) {
    return { completionRate: 0, completedQuantity: 0, targetQuantity: 0 }
  }

  const typeData = progressData.value.type_progress_data[requirementType]
  if (!typeData) {
    return { completionRate: 0, completedQuantity: 0, targetQuantity: 0 }
  }

  return {
    completionRate: typeData.completion_rate,
    completedQuantity: typeData.completed_quantity,
    targetQuantity: typeData.target_quantity
  }
}

// 获取冻结进度百分比（仅用于高价值外链）
const getFrozenProgress = (requirementType: string) => {
  if (requirementType !== '高价值外链' || !progressData.value?.type_progress_data) {
    return 0
  }

  const typeData = progressData.value.type_progress_data[requirementType]
  if (!typeData || !typeData.frozen_count || !typeData.target_quantity) {
    return 0
  }

  return (typeData.frozen_count / typeData.target_quantity) * 100
}

// 获取冻结数量（仅用于高价值外链）
const getFrozenCount = (requirementType: string) => {
  if (requirementType !== '高价值外链' || !progressData.value?.type_progress_data) {
    return 0
  }

  const typeData = progressData.value.type_progress_data[requirementType]
  return typeData?.frozen_count || 0
}

// 获取正常完成进度百分比（已完成数量 / 总数量）
const getNormalProgress = (requirementType: string) => {
  if (requirementType !== '高价值外链' || !progressData.value?.type_progress_data) {
    return 0
  }

  const typeData = progressData.value.type_progress_data[requirementType]
  if (!typeData || !typeData.target_quantity) {
    return 0
  }

  // 正常完成进度 = 已完成数量 / 总数量 * 100
  return (typeData.completed_quantity / typeData.target_quantity) * 100
}

// 根据进度获取项目状态
const getItemStatusByProgress = (requirementType: string) => {
  const progress = getRequirementProgress(requirementType)

  if (progress.completionRate >= 100) {
    return { text: '已完成', class: 'completed' }
  } else {
    return { text: '待处理', class: 'pending' }
  }
}

const getCompletedRequirementsCount = () => {
  if (!progressData?.value?.type_progress_data) return 0
  return Object.values(progressData.value.type_progress_data).filter(req => req.completion_rate >= 100).length
}

// 解析价格字符串为数字
const parsePrice = (priceStr: string | number | undefined | null): number => {
  if (typeof priceStr === 'number') return priceStr
  if (!priceStr) return 0

  // 移除货币符号和空格，然后转换为数字
  const cleanPrice = String(priceStr).replace(/[$￥,\s]/g, '')
  const parsed = parseFloat(cleanPrice)
  return isNaN(parsed) ? 0 : parsed
}

// 计算金额使用百分比
const getAmountPercentage = (type: 'freeze_price' | 'submit_price' | 'confirm_price') => {
  if (!progressData.value?.type_progress_data.金额使用) return 0

  const totalPriceRaw = progressData.value?.amount_usage?.total_price || props.project.contract_terms?.amount || 0
  const totalPrice = parsePrice(totalPriceRaw)

  if (totalPrice === 0) return 0
  const typePrice = parsePrice(progressData.value.type_progress_data.金额使用[type])
  return (typePrice / totalPrice) * 100
}

// 获取质量检查数据
const getQualityCheckData = (requirementType: string) => {
  if (!progressData.value?.type_progress_data) return null

  const typeData = progressData.value.type_progress_data[requirementType]
  if (!typeData?.quality_check || !typeData.quality_check.has_requirements) return null

  return typeData.quality_check
}

// 获取质量检查标签
const getQualityCheckLabel = (requirementType: string) => {
  const qualityData = getQualityCheckData(requirementType)
  if (!qualityData?.quality_requirements) return ''

  const requirements = qualityData.quality_requirements
  if (requirements.as) {
    return `AS > ${requirements.as}`
  } else if (requirements.da) {
    return `DA > ${requirements.da}`
  }
  return '质量检查'
}

// 组件挂载时获取进度数据
onMounted(() => {
  fetchProgressData()
})
</script>

<style scoped>
.project-row {
  padding: 20px 24px;
  border-bottom: 1px solid #f3f4f6;
  display: grid;
  grid-template-columns: 0.6fr 1.8fr 0.8fr 0.8fr 2.5fr 0.9fr 120px;
  gap: 15px;
  align-items: flex-start;
  transition: background 0.2s;
}

.project-row:hover {
  background: #f9fafb;
}

.project-row:last-child {
  border-bottom: none;
}

.project-id {
  font-size: 14px;
  color: #6b7280;
  font-family: 'Monaco', 'Menlo', monospace;
  font-weight: 500;
}

.project-info h4 {
  font-size: 16px;
  color: #1f2937;
  margin-bottom: 4px;
}

.project-info p {
  font-size: 13px;
  color: #6b7280;
}

.project-code {
  font-family: 'Monaco', 'Menlo', monospace;
  font-size: 12px;
  color: #6b7280;
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
}

.status-badge.pending {
  background: #fef3c7;
  color: #92400e;
}

.status-badge.warning {
  background: #fed7d7;
  color: #c53030;
}

.status-badge.completed {
  background: #d1fae5;
  color: #065f46;
}

.status-badge.deleted {
  background: #f15574;
  color: #ffffff;
}

.progress-bar {
  width: 100%;
  height: 6px;
  background: #e5e7eb;
  border-radius: 3px;
  overflow: hidden;
}

.progress-bar.dual-color {
  position: relative;
}

.progress-fill {
  height: 100%;
  background: #6366f1;
  transition: width 0.3s;
}

.progress-fill-frozen {
  height: 100%;
  background: #c026d3;
  /* 紫红色 - 冻结进度 */
  transition: width 0.3s;
  position: absolute;
  left: 0;
  top: 0;
}

.progress-fill-normal {
  height: 100%;
  background: #6366f1;
  /* 蓝色 - 正常完成进度 */
  transition: width 0.3s;
  position: absolute;
  top: 0;
}

.progress-text {
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
}

.frozen-progress-info {
  font-size: 11px;
  color: #92400e;
  margin-top: 2px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.frozen-indicator {
  font-size: 10px;
}

.quality-progress {
  margin-top: 6px;
}

.quality-progress-bar {
  width: 100%;
  height: 4px;
  background: #f3f4f6;
  border-radius: 2px;
  overflow: hidden;
}

.quality-progress-fill {
  height: 100%;
  background: #fbbf24;
  transition: width 0.3s;
}

.quality-progress-text {
  font-size: 11px;
  color: #92400e;
  margin-top: 2px;
  font-weight: 500;
}

.progress-loading {
  font-size: 12px;
  color: #6b7280;
  font-style: italic;
  padding: 8px 0;
}

.progress-error {
  font-size: 12px;
  color: #dc2626;
  padding: 8px 0;
}

.project-type {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
  margin-bottom: 4px;
}

.contract-amount {
  font-size: 13px;
  color: #059669;
  font-weight: 600;
}

.manager-info {
  font-size: 14px;
  color: #374151;
}

.items-summary {
  font-size: 13px;
  min-height: 60px;
}

.no-items {
  color: #9ca3af;
  font-style: italic;
  padding: 8px 0;
}

.item-row {
  display: flex;
  flex-direction: column;
  margin-bottom: 8px;
  padding: 8px;
  background: #f9fafb;
  border-radius: 6px;
  border-left: 3px solid #e5e7eb;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.item-name {
  color: #374151;
  font-weight: 600;
  font-size: 14px;
}

.item-status {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 500;
}

.item-status.pending {
  background: #fef3c7;
  color: #92400e;
}

.item-status.completed {
  background: #d1fae5;
  color: #065f46;
}

.item-details {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  font-size: 12px;
  color: #6b7280;
}

.item-detail-tag {
  background: #ffffff;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
  font-size: 11px;
}

.item-quantity {
  background: #dbeafe;
  color: #1e40af;
  font-weight: 500;
}

.item-price {
  background: #d1fae5;
  color: #059669;
  font-weight: 600;
}

.item-da {
  background: #fef3c7;
  color: #92400e;
}

.item-as {
  background: #fef3c7;
  color: #92400e;
}

.item-dofollow {
  background: #e0e7ff;
  color: #3730a3;
}

.item-count {
  background: #fef3c7;
  color: #92400e;
  font-weight: 500;
}

.item-notes {
  margin-top: 6px;
  padding: 4px 8px;
  background: #f3f4f6;
  border-radius: 4px;
  font-size: 11px;
  color: #6b7280;
  font-style: italic;
}

.items-total {
  margin-top: 12px;
  padding: 8px;
  background: #f3f4f6;
  border-radius: 4px;
  font-weight: 600;
  color: #374151;
  font-size: 12px;
}

.total-amount {
  text-align: center;
  margin-bottom: 4px;
}

.completion-info {
  text-align: center;
  margin-bottom: 8px;
}

.amount-usage {
  margin-top: 8px;
}

.amount-usage-header {
  font-size: 11px;
  color: #6b7280;
  margin-bottom: 4px;
  text-align: center;
}

.amount-progress-bar {
  width: 100%;
  height: 8px;
  background: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  margin-bottom: 6px;
}

.amount-segment {
  height: 100%;
  transition: width 0.3s;
}

.amount-segment.freeze {
  background: #fbbf24;
  /* 黄色 - 冻结 */
}

.amount-segment.submit {
  background: #60a5fa;
  /* 蓝色 - 提交 */
}

.amount-segment.confirm {
  background: #34d399;
  /* 绿色 - 确认 */
}

.amount-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  font-size: 10px;
  justify-content: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 12px;
  color: #6b7280;
}

.legend-color {
  width: 8px;
  height: 8px;
  border-radius: 2px;
  display: inline-block;
}

.legend-color.freeze {
  background: #fbbf24;
}

.legend-color.submit {
  background: #60a5fa;
}

.legend-color.confirm {
  background: #34d399;
}

.legend-color.remaining {
  background: #e5e7eb;
}

.legend-color.adsy {
  background: #c026d3;
}

.date-info {
  font-size: 13px;
  color: #6b7280;
}

.project-timeline {
  margin-top: 8px;
}

.timeline-progress-bar {
  width: 100%;
  height: 4px;
  background: #e5e7eb;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 4px;
}

.timeline-progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #10b981 0%, #059669 50%, #047857 100%);
  transition: width 0.3s ease;
  border-radius: 2px;
}

.timeline-text {
  font-size: 11px;
  color: #6b7280;
  text-align: center;
}

.actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #d1d5db;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
}

.action-btn:hover {
  background: #f9fafb;
}

.action-btn.primary {
  background: #6366f1;
  color: white;
  border-color: #6366f1;
}

.action-btn.warning {
  background: #f59e0b;
  color: white;
  border-color: #f59e0b;
}
</style>